<template>


  <!-- 视频页面 -->
  <view class="live">

    <!-- 全局导航栏 -->
    <toptab-Bar></toptab-Bar>


    <!-- 头部 -->
    <view class="live__header flex live-wrapper">
      <!-- 			<view class="flex">
              <view class="live__header-text">直播类型</view>
              <view class="live__header-text">直播状态</view>
            </view> -->

      <van-dropdown-menu class="live__header-drop">
        <van-dropdown-item :value="headerText1" :options= "headerOption1" />
        <van-dropdown-item :value="headerText2" :options="headerOption2" />
      </van-dropdown-menu>

      <view class="flex">
        <image src="/static/date.png" mode="aspectFill" class="live__header-icon"></image>
        <image
            v-if="displayMode===1"
            src="/static/vertical.png" mode="aspectFill" class="live__header-icon"
            @click="changDisplayMode"
        ></image>

        <image
            v-else
            src="/static/horizontal.png" mode="aspectFill" class="live__header-icon"
            @click="changDisplayMode"
        ></image>
      </view>
    </view>

    <!-- <keep-alive> -->
    <view class="live__items flex live-wrapper"
          v-show="displayMode===1"
    >
      <!-- 跳转写在了组件里面 -->
      <live-ver-display-item
          v-for="item in displayItems"
          :key="item.id"
          :data= "item"

      ></live-ver-display-item>
    </view>
    <!-- </keep-alive> -->

    <!-- <keep-alive> -->
    <view class="live__items flex live-wrapper"
          v-show="displayMode===2"
    >
      <live-hor-display-item
          v-for="item in displayItems"
          :key="item.id"
          :data= "item"

      ></live-hor-display-item>
    </view>
    <!-- </keep-alive> -->

  </view>
</template>

<script setup>
import toptabBar from  '@/pages/index/toptabbar/tabbar.vue';
import liveVerDisplayItem from '@/components/liveVerDisplayItem/liveVerDisplayItem.vue';
import liveHorDisplayItem from '@/components/liveHorDisplayItem/liveHorDisplayItem.vue'
import { onActivated, onBeforeMount, onMounted, onUnmounted, ref } from 'vue';
import decLiveApi from "/api/dec/decIndex/decLiveApi";
import {onReachBottom} from '@dcloudio/uni-app';



const  headerText1 = ref(0);
const  headerText2 = ref('a');

const headerOption1 = ref([
  { text: '直播类型', value: 0 },
  { text: '全部类型', value: 1 },
  { text: '体育', value: 2 },
  { text: '文艺', value: 3 },
]);

const headerOption2 = ref([
  { text: '直播状态', value: 'a' },
  { text: '全部状态', value: 'b' },
  { text: '即将直播', value: 'c' },
  { text: '直播中', value: 'd' },
  { text: '已结束', value: 'e' },
])

let page = 0;
const pageSize = 10;

// 	// 微信小程序平台：目前仅支持 flv, rtmp 格式
// 	// 非微信小程序平台：m3u8, flv, rtmp 格式
const liveItems = ref([]);			// 存放直播
const liveReplayItems = ref([]);	// 存放直播回放
const livePreviewItems = ref([]);	// 存放直播预告
const displayItems = ref([]);		// 所有的直播

// 1表示垂直展示，2表示水平展示
const displayMode = ref(1);

function changDisplayMode(){
  if(displayMode.value===1){
    displayMode.value = 2;
  }else{
    displayMode.value = 1;
  }
}

// 防抖函数，写给上拉的
function debounce(fn, delay) {
  let timer = null; // 用来存储定时器的 ID

  return function (...args) {
    // 每次触发时，如果之前已经有一个定时器了，就清除它
    if (timer) {
      clearTimeout(timer);
    }

    // 重新设置一个新的定时器
    timer = setTimeout(() => {
      // 确保 this 上下文和参数的正确传递
      fn.apply(this, args);
    }, delay);
  };
}


async function init(){
  // displayItems.value.length = 0;
  page++
  await Get_Gf_live('1',10,page);
  await Promise.all([
    Insert_LiveDetail_2_liveItems(),
    Insert_LiveDetail_2_liveReplayItems(),
    Insert_LiveDetail_2_livePreviewItems(),
  ]);
  displayItems.value.push(...liveItems.value,...liveReplayItems.value,...livePreviewItems.value);
  console.log("displayItems", displayItems.value);
}

async function Get_Gf_live(get_option='1', per_page=10,page) {
  let params = {
    get_option: get_option,
    per_page : per_page,
    page : page,
    // state:'2'
  };
  // console.log('par',params);
  try {
    // 清空上一页的值
    liveItems.value.length = 0;
    liveReplayItems.value.length = 0;

    const res = await decLiveApi.Gf_live_API(params);
    let liveData = res.datas;
    liveData.forEach((item) => {
      // 1-即将直播，2-直播中，3-回放
      if(item.state_id == '2' || item.state_id == 2) {  // 直播中
        if(item.is_rtmp == '1') { // 直播中状态时是否推流0-未推流，1-推流
          // 正在直播，并且在推流
          liveItems.value.push(item);
        }
      }
      else if(item.state_id == '3' || item.state_id == 3) { // 直播回放
        liveReplayItems.value.push(item);
      }
      else if(item.state_id == '1' || item.state_id == 1) { // 直播预告
        livePreviewItems.value.push(item);
      }
    });
  } catch(err) {
    console.error('Gf_live_API 失败', err);
  }
}

// 获取直播详情
function Get_Live_detail_API(live_id) {
  let params = {
    live_id: live_id,
  };
  return decLiveApi.Live_detail_API(params).then((res) => {
    // console.log('Get_Live_detail_API 成功', res);
    return res;
  }).catch((err) => {
    console.error('Get_Live_detail_API 失败', err);
    return Promise.reject(err);
  })
}

// 把直播详情塞入liveItems的detail属性中，直播
async function Insert_LiveDetail_2_liveItems() {
  if(liveItems.value.length > 0) {
    const detailPromises = liveItems.value.map(item => Get_Live_detail_API(item.id));
    const itemDetails = await Promise.all(detailPromises);
    for (let i = 0; i < itemDetails.length; i++) {
      const item = liveItems.value[i];
      if (itemDetails[i]) {
        item.detail = itemDetails[i];
        item.url = itemDetails[i].datas.live_source_rtmp_h;
        item.data_type = itemDetails[i].datas.data_type;						// 类型
        item.title = itemDetails[i].datas.title;
        item.live_type_name = itemDetails[i].datas.live_type_name;
        item.club_logo = itemDetails[i].datas.club_logo;
        item.club_name = itemDetails[i].datas.club_name;
        item.cut_path = itemDetails[i].datas.cut_path;
        item.clicked = itemDetails[i].datas.clicked;
      }
      else {
        item.detail = {};
        console.log("itemDetail undefinded");
      }
    }
  }
  else{
    console.log("liveItems为空，请检查直播列表");
  }
}

// 把直播回放详情塞入liveReplayItems的detail属性中，直播回放
async function Insert_LiveDetail_2_liveReplayItems() {
  if(liveReplayItems.value.length > 0) {
    const detailPromises = liveReplayItems.value.map(item => Get_Live_detail_API(item.id));
    const itemDetails = await Promise.all(detailPromises);
    for (let i = 0; i < itemDetails.length; i++) {
      const item = liveReplayItems.value[i];
      if (itemDetails[i]) {
        item.detail = itemDetails[i];
        item.url = itemDetails[i].datas.live_source_rtmp_h;
        item.data_type = itemDetails[i].datas.data_type;						// 类型
        item.title = itemDetails[i].datas.title;
        item.live_type_name = itemDetails[i].datas.live_type_name;
        item.club_logo = itemDetails[i].datas.club_logo;
        item.club_name = itemDetails[i].datas.club_name;
        item.cut_path = itemDetails[i].datas.cut_path;
      }
      else {
        item.detail = {};
        console.log("itemDetail undefinded");
      }
    }
  }
  else{
    console.log("liveReplayItems为空，请检查直播回放列表");
  }
}

// 把直播回放详情塞入liveReplayItems的detail属性中，直播预告
async function Insert_LiveDetail_2_livePreviewItems() {
  if(livePreviewItems.value.length > 0) {
    const detailPromises = livePreviewItems.value.map(item => Get_Live_detail_API(item.id));
    const itemDetails = await Promise.all(detailPromises);
    for (let i = 0; i < itemDetails.length; i++) {
      const item = livePreviewItems.value[i];
      if (itemDetails[i]) {
        item.detail = itemDetails[i];
        item.url = itemDetails[i].datas.live_source_rtmp_h;
        item.data_type = itemDetails[i].datas.data_type;						// 类型
        item.title = itemDetails[i].datas.title;
        item.live_type_name = itemDetails[i].datas.live_type_name;
        item.club_logo = itemDetails[i].datas.club_logo;
        item.club_name = itemDetails[i].datas.club_name;
        item.cut_path = itemDetails[i].datas.cut_path;
      }
      else {
        item.detail = {};
        console.error("itemDetail undefinded");
      }
    }
  }
  else{
    console.log("livePreviewItems，请检查直播回放列表");
  }
}

const debounceInit = debounce(init,1000);

// 滑到底部上拉刷新函数
onReachBottom(()=>{
  console.log('上拉一次',page);
  debounceInit();
})

onMounted(()=>{
  // console.log('live页面挂载');
  init();
})

onUnmounted(()=>{
  // console.log('live页面卸载');
})




</script>

<style lang="scss" scoped>
// 去除vant的样式
::v-deep .van-dropdown-menu{
  background-color: transparent;
  box-shadow: none;
}

.live{
  width: 100%;

  &-wrapper{
    box-sizing: border-box;
    padding: 0 20rpx;
  }

  &__header{
    width: 100%;
    height: 97rpx;
    background-color: #f7f7f9;
    justify-content: space-between;

    // 下拉菜单
    &-drop{
      width: 400rpx;
    }

    &-text{

    }

    &-icon{
      width: 40rpx;
      height: 40rpx;
      margin-left: 48rpx;
    }
  }

  &__items{
    width: 100%;
    flex-wrap: wrap;
    justify-content: space-between;
    background-color: #fff;
    padding-top: 23rpx;
  }
}


</style>
